<template>
	<view class="qrcode-container">
		<view class="qrcode-box">
			<view class="title">我的二维码</view>
			<view class="qrcode-wrapper">
				<image v-if="qrCodeUrl" :src="qrCodeUrl" mode="aspectFit" class="qrcode-image"></image>
				<view v-else class="loading">
					<uni-icons type="spinner-cycle" size="24" color="#409EFF"></uni-icons>
					<text>生成中...</text>
				</view>
			</view>
			<view class="user-info">
				<text class="username">{{ userInfo.userName }}</text>
				<text class="username">工号：{{ userInfo.employeeId }}</text>
				<text class="username">等级：{{ userInfo.level }}</text>
			</view>
			<!-- <button v-if="isBusiness" class="scan-btn cu-btn block bg-blue lg round" @click="scanQrCode">
				扫码分配号码
			</button> -->
		</view>
	</view>
</template>

<script>
	import { getUser } from '@/api/system/user'
	import { listInfo, assignNumber as assignApi, getUserList, generateFamaQRCode } from '@/api/info.js'

	export default {
		data() {
			return {
				userInfo: {},
				qrCodeUrl: '',
				isBusiness: false,
				scanResult: null
			}
		},
		onLoad() {
			this.getUserInfo()
			const roles = uni.getStorageSync('roles') || []
			this.isBusiness = roles.includes('yewuyuan')
		},
		methods: {
			getUserInfo() {
				const userInfo = uni.getStorageSync('userInfo')
				if (userInfo && userInfo.user) {
					this.userInfo = userInfo.user
					// 主动查一次详细信息，补充level字段
					getUser(this.userInfo.userId).then(res => {
						if (res.code === 200 && res.data) {
							this.userInfo.level = res.data.level || '暂无'
						}
						this.generateQRCode()
					})
				} else {
					this.$modal.msgError('未获取到用户信息')
				}
			},
			generateQRCode() {
				const qrContent = JSON.stringify({
					userId: this.userInfo.userId,
					type: 'salesperson',
					timestamp: new Date().toISOString().split('T')[0]
				})
				generateFamaQRCode({ content: qrContent }).then(res => {
					if (res.code === 200 && res.url) {
						this.qrCodeUrl = res.url
					} else {
						uni.showToast({ title: '生成二维码失败', icon: 'none' })
					}
				}).catch(err => {
						console.error('生成二维码失败：', err)
					uni.showToast({ title: '生成二维码失败', icon: 'none' })
				})
			},
			scanQrCode() {
				uni.scanCode({
					onlyFromCamera: true,
					success: async (res) => {
						try {
							const qrData = JSON.parse(res.result)
							console.log('扫码结果：', qrData)
							
							// 判断是否是发码二维码
							if (qrData.type !== 'fama') {
								uni.showToast({
									title: '无效的发码二维码',
									icon: 'none'
								})
								return
							}
							
							// 验证日期
							const today = new Date().toISOString().split('T')[0]
							if (qrData.timestamp !== today) {
								uni.showToast({
									title: '二维码已过期',
									icon: 'none'
								})
								return
							}
							
							// 获取当前业务员信息
							const userInfo = uni.getStorageSync('userInfo')
							if (!userInfo || !userInfo.user) {
								uni.showToast({
									title: '未获取到用户信息',
									icon: 'none'
								})
								return
							}
							
							// 显示确认对话框
							uni.showModal({
								title: '分配号码',
								content: `是否要为业务员 ${userInfo.user.userName} 分配号码？`,
								success: async (modalRes) => {
									if (modalRes.confirm) {
										try {
											const assignRes = await assignApi({
												userId: userInfo.user.userId,
												employeeId: userInfo.user.employeeId,
												level: '暂无'
											})
											
											if (assignRes.code === 200) {
												uni.showToast({
													title: '分配成功',
													icon: 'success'
												})
											} else {
												uni.showToast({
													title: assignRes.msg || '分配失败',
													icon: 'none'
												})
											}
										} catch (error) {
											console.error('分配号码失败：', error)
											uni.showToast({
												title: '分配失败，请重试',
												icon: 'none'
											})
										}
									}
								}
							})
						} catch (error) {
							console.error('处理扫码结果失败：', error)
							uni.showToast({
								title: '无效的二维码',
								icon: 'none'
							})
						}
					},
					fail: () => {
						uni.showToast({
							title: '扫码失败，请重试',
							icon: 'none'
						})
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
.qrcode-container {
	min-height: 100vh;
	background-color: #f5f7fa;
	padding: 30rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.qrcode-box {
	background: #fff;
	border-radius: 20rpx;
	padding: 40rpx;
	width: 80%;
	box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.05);
	text-align: center;
	
	.title {
		font-size: 36rpx;
		color: #333;
		font-weight: bold;
		margin-bottom: 40rpx;
	}
	
	.qrcode-wrapper {
		width: 400rpx;
		height: 400rpx;
		margin: 0 auto 40rpx;
		background: #fff;
		padding: 20rpx;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
		
		.qrcode-image {
			width: 100%;
			height: 100%;
		}
		
		.loading {
			width: 100%;
			height: 100%;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			color: #909399;
			font-size: 28rpx;
			
			.uni-icons {
				margin-bottom: 20rpx;
			}
		}
	}
	
	.user-info {
		.username {
			font-size: 32rpx;
			color: #333;
			font-weight: bold;
			display: block;
			margin-bottom: 10rpx;
		}
		
		.employee-id {
			font-size: 28rpx;
			color: #909399;
		}
	}

	.scan-btn {
		margin-top: 40rpx;
		width: 80%;
		height: 88rpx;
		line-height: 88rpx;
		font-size: 32rpx;
		color: #fff;
		background-color: #5e86ff;
		border-radius: 44rpx;
		display: block;
		margin-left: auto;
		margin-right: auto;
	}
}
</style>
